package com.bluepunch.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bluepunch.entity.*;
import com.bluepunch.service.*;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bluepunch
 * @since 2023-10-07
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private BlogService blogService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserUserService userUserService;
    @Autowired
    private CollectibleService collectibleService;

    //用户中心主页
    @GetMapping("/user/{uid}")
    public String userIndex(@PathVariable String uid, Model model){
        // 用户信息回填
        userInfoCallBack(uid,model);
        // 用户的博客列表
        Page<Blog> pageParam = new Page<>(1, 10);
        blogService.page(pageParam,new QueryWrapper<Blog>().eq("author_id", uid)
                                                         .orderByDesc("create_time"));
        // 结果
        List<Blog> blogList = pageParam.getRecords();
        model.addAttribute("blogList",blogList);
        model.addAttribute("pageParam",pageParam);

        return "user/index";
    }

//···································好友··········································

    @GetMapping("/user/friend/add/{uid}/{fid}")
    // 关注用户
    public String addFriend(@PathVariable String uid,@PathVariable String fid,Model model){
        // 用户信息回填
        userInfoCallBack(uid,model);

        //如果两个id不同  不能自己关注自己
        if(!uid.equals(fid)){
            UserUser one = userUserService.getOne(new QueryWrapper<UserUser>()
                    .eq("user_id", uid).eq("friend_id", fid));
            //如果好友关系不存在建立好友关系
            if (one==null){
                UserUser friend = new UserUser();

                //用户uid对用户fid建立好友关系
                friend.setUserId(Long.valueOf(uid));
                friend.setFriendId(Long.valueOf(fid));
                userUserService.save(friend);
                //用户fid对用户uid建立好友关系
                friend.setUserId(Long.valueOf(fid));
                friend.setFriendId(Long.valueOf(uid));
                userUserService.save(friend);
            }
        }
        //返回好友页面
        return "user/user-friend";
    }

    @GetMapping("/user/friend/blog/{fid}")
    // 查看关注用户的博客
    public String showFriendBlog(@PathVariable String fid,Model model){
        //好友信息回传
        userInfoCallBack(fid,model);

        // 好友的博客列表
        Page<Blog> pageParam = new Page<>(1, 10);
        blogService.page(pageParam,new QueryWrapper<Blog>().eq("author_id", fid)
                .orderByDesc("create_time"));
        // 结果
        List<Blog> blogList = pageParam.getRecords();
        model.addAttribute("blogList",blogList);
        model.addAttribute("pageParam",pageParam);

        return "user/index";
    }

    @GetMapping("/user/friend/{uid}")
    // 显示所有我的关注用户
    public String showAllFriend(@PathVariable String uid, Model model){
        // 用户信息回填
        userInfoCallBack(uid,model);

        //查询好友表  将uid的所有好友按照时间顺序查出
        List<UserUser> list = userUserService.list(new QueryWrapper<UserUser>()
                .eq("user_id",uid)
                .orderByAsc("create_time"));
        //从好友表中查询需要的信息封装到friends
        List<User> friends = new ArrayList<>();
        for (UserUser uu : list){
            //将好友表查到的fid拿到用户表查询好友信息
            User user = userService.getOne(new QueryWrapper<User>().eq("id",uu.getFriendId()));
            //用户存在才放入friends
            if(user!=null){
                friends.add(user);
            }
        }
        //分页对象
        Page<User> pageParam = new Page<>(1, 10);
        pageParam.setRecords(friends);
        //将信息传回页面
        model.addAttribute("friendList",friends);
        model.addAttribute("pageParam",pageParam);

        //返回好友页面
        return "user/user-friend";
    }

    @GetMapping("/user/friend/delete/{uid}/{fid}")
    // 删除我关注的用户
    public String deleteFriend(@PathVariable String uid,@PathVariable String fid,Model model){
        // 用户信息回填
        userInfoCallBack(uid,model);

        //如果两个id不同  不能自己删除自己
        if(!uid.equals(fid)){
            //用户uid对用户fid删除好友关系
            userUserService.remove(new QueryWrapper<UserUser>()
                    .eq("user_id",uid).eq("friend_id",fid));
            //用户fid对用户uid删除好友关系
            userUserService.remove(new QueryWrapper<UserUser>()
                    .eq("user_id",fid).eq("friend_id",uid));
        }

        //返回好友页面 请求重定向(redirect)将请求重新定位到资源
        return "redirect:/user/friend/"+uid;
    }

//···································个人信息··········································
    // 更新个人信息页面
    /*
    * @param uid
    * @param model
    * */
    @GetMapping("/user/update/{uid}")
    public String Update(@PathVariable String uid, Model model){
        // 用户信息回填
        userInfoCallBack(uid,model);

        User user = userService.getById(uid);
        System.out.println("UserController-Update:"+user);
        model.addAttribute("user",user);
        return "user/update";
    }

    // 上传地址
    @Value("${file.upload.path}")
    private String filePath;

    /**
     * 文件上传
     * @param attach
     * @param model
     * @return
     */
    @PostMapping("/user/toUpdate/{uid}")
    public String toUpdate(@PathVariable String uid,
                           @RequestPart("avatar")MultipartFile attach, Model model){
        // 用户信息回填
        userInfoCallBack(uid,model);

        User user = userService.getById(uid);

        // 判断文件是否为空,不为空则进行文件上传
        if(!attach.isEmpty()){
            // 获取源文件名称
            String fileName = attach.getOriginalFilename();
            // 获取源文件后缀名
            String suffix = FilenameUtils.getExtension(fileName);
            // 使用UUID重命名文件名称
            String newFileName = UUID.randomUUID().toString().replace("-","")+(".")+suffix;
            // 使用日期解决同一文件夹中文件过多问题(以当前日期命名文件夹)
            String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            // 组装最终文件名
            String finalName = datePath+"/"+newFileName;
            //获取当前工程目录
            String projectPath = System.getProperty("user.dir");
            // 构建文件对象 projectPath+ "/src/main/java/resources/templates/upload/"
            File dest = new File(projectPath + "/templates/upload/" + finalName);
            System.out.println(projectPath + "/templates/upload/");
            //输出路径
            //System.out.println("UserController-toUpdate:"+projectPath+"/upload/" + finalName);
            // 判断该文件夹是否存在,不存在则创建
            if(!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs(); // 创建文件夹
            }

            // 将文件保存到硬盘
            try {
                attach.transferTo(dest);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            //获取前端的信息
            String username = (String) model.getAttribute("username");

            // 将当前图片放到模型中,便于页面回显
            model.addAttribute("avatar",finalName);
            user.setAvatar(finalName);
            userService.update(user,new QueryWrapper<User>().eq("id",user.getId()));
            model.addAttribute("user",user);
        }else {
            model.addAttribute("avatar",user.getAvatar());
        }
        // 返回页面(该页面是templates目录下的页面)
        return "user/update";
    }


    // 用户信息回填
    private void userInfoCallBack(String uid,Model model){
//        UserInfo userInfo = userInfoService.getById(uid);
//        model.addAttribute("userInfo",userInfo);
//        if (userInfo.getHobby()!=null && !userInfo.getHobby().equals("")){
//            String[] hobbys = userInfo.getHobby().split(",");
//            model.addAttribute("infoHobbys",hobbys);
//        }
        // 获取用户的好友，博客，回复数
        int blogCount = blogService.count(new QueryWrapper<Blog>().eq("author_id", uid));
        int friendCount = userUserService.count(new QueryWrapper<UserUser>().eq("user_id", uid));
        int commentCount = commentService.count(new QueryWrapper<Comment>().eq("user_id", uid));
        model.addAttribute("blogCount",blogCount);
        model.addAttribute("friendCount",friendCount);
        model.addAttribute("commentCount",commentCount);

        User user = userService.getById(uid);
        model.addAttribute("avatar",user.getAvatar());
        model.addAttribute("username",user.getUsername());
    }

//···································个人收藏··········································

    @GetMapping("/user/collectible/vis/{cid}")
    //设置收藏是否公开 可见性
    public String visCollectible(@PathVariable String cid,Model model){



        return "user/user-collectible";
    }

    @GetMapping("/user/collectible/delete/{cid}")
    //删除收藏
    public String addCollectible(@PathVariable String cid,Model model){

        return "user/user-collectible";
    }

    @GetMapping("/user/collectible/add/{bid}")
    //添加收藏
    public String deleteCollectible(@PathVariable String bid,Model model){


        return "user/user-collectible";
    }
    @GetMapping("/user/collectible/{uid}")
    //显示收藏
    public String Collectible(@PathVariable String uid,Model model){
        //用户信息回显
        userInfoCallBack(uid,model);
        //查询收藏表 按照创建时间排序
        List<Collectible> collectibleList = collectibleService.list(new QueryWrapper<Collectible>()
                .eq("user_id", uid).orderByDesc("create_time"));
        //依据收藏信息查询对应的博客
        List<Blog> blogList = new ArrayList<>();
        for (Collectible c : collectibleList){
            Blog blog = blogService.getById(c.getBlogId());
            blogList.add(blog);
        }
        //信息回传
        model.addAttribute("blogList",blogList);
        model.addAttribute("collectibleList",collectibleList);
        Page<Collectible> pageParam = new Page<>(1, 10);
        pageParam.setRecords(collectibleList);
        model.addAttribute("pageParam",pageParam);

        return "user/user-collectible";
    }
}

